package com.cheryjb.examples.spring.transactions.managers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.cheryjb.examples.spring.transactions.model.Person;

/**
 * Simple implementation of PersonManager. Deal with the basic logic. Dao logic
 * is deferred to PersonManagerDao
 * 
 * @author cheryjb
 * 
 */
public class PersonManagerImpl implements PersonManager {

	private final PersonManagerDao personManagerDao;

	public PersonManagerImpl(final PersonManagerDao personManagerDao) {
		this.personManagerDao = personManagerDao;
	}

	public void clearAll() {
		personManagerDao.clearAll();

	}

	public void addPerson(final Person person) {
		Assert.notNull(person, "person cannot be null");
		Assert.notNull(person.getId(), "person id cannot be null");

		personManagerDao.addPerson(person);

	}

	public Person getPerson(final String id) {
		Assert.notNull(id, "person id cannot be null");

		return personManagerDao.getPerson(id);
	}

	public List<Person> getPersons(final String[] ids) {
		Assert.notNull(ids, "ids cannot be null");

		final List<Person> persons = new ArrayList<Person>();

		for (final String id : ids) {
			persons.add(getPerson(id));
		}

		return persons;
	}

	public void doOperation(final Person person) {
		Assert.notNull(person, "person cannot be null");

		personManagerDao.doOperation(person);
	}

	@Transactional
	public void doOperation(final List<Person> persons) {
		Assert.notNull(persons, "The list of persons cannot be null");

		// because this method is transactional, if one of the atomic operation
		// doOperation(person) fails, all the previous operations are rollbacked
		for (final Person person : persons) {
			this.doOperation(person);
		}
	}

	public void dropRepository() {
		this.personManagerDao.dropRepository();
	}

	public void createRepository() {
		this.personManagerDao.createRepository();
	}

}
